package wiki.laona.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import wiki.laona.constant.EnumFileType;
import wiki.laona.constant.MinioProp;
import wiki.laona.pojo.Users;
import wiki.laona.pojo.vo.UsersVO;
import wiki.laona.service.IMinioService;
import wiki.laona.service.IOssService;
import wiki.laona.service.center.CenterUserService;
import wiki.laona.utils.CookieUtils;
import wiki.laona.utils.JsonResult;
import wiki.laona.utils.JsonUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * @author laona
 * @decription 上传接口
 * @since 2022-06-30 22:30
 **/
@Slf4j
@Api(value = "文件上传相关接口", tags = "文件上传相关接口")
@RestController
public class UploadController extends BaseController {

    @Resource
    private IMinioService minioService;
    @Resource
    private MinioProp minioProp;
    @Resource
    private CenterUserService centerUserService;
    @Resource
    private IOssService ossService;

    @ApiOperation(value = "minio上传文件接口")
    @PostMapping("/minio/upload")
    public JsonResult minioUpload(@ApiParam(value = "上传的文件", required = true) MultipartFile multiFile,
                             @ApiParam(value = "文件类型") String type) throws Exception {

        JsonResult result = JsonResult.ok();
        String filename = multiFile.getOriginalFilename();
        InputStream stream = multiFile.getInputStream();

        EnumFileType fileType = ObjectUtils.nullSafeEquals(EnumFileType.IMAGE.type, type)
                ? EnumFileType.IMAGE
                : EnumFileType.OTHER;

        String path = minioService.upload(filename, stream, fileType);
        result.setData(path);

        return result;
    }


    @ApiOperation(value = "minio用户头像修改", httpMethod = "POST")
    @PostMapping("/minio/uploadFace")
    public JsonResult minioUploadFace(@ApiParam(name = "userId", value = "用户id", required = true)
                                 @RequestParam String userId,
                                 @ApiParam(name = "file", value = "用户头像", required = true) MultipartFile file,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {

        String path = "";

        // 开始上传
        if (ObjectUtils.isEmpty(file)) {
            return JsonResult.errorMsg("文件不能为空!");
        }

        // 获取上传文件的文件名称
        String originalFilename = file.getOriginalFilename();

        if (StringUtils.hasText(originalFilename)) {
            // 文件重命名  laona-face.png -> ["laona-face", "png"]
            String[] fileNameArr = originalFilename.split("\\.");

            String suffix = fileNameArr[fileNameArr.length - 1];

            // 格式判断 "jpg", "jpg", "jpeg"
            final String jpgStyle = "jpg";
            final String jpegStyle = "jpeg";
            final String pngStyle = "png";

            if (!jpgStyle.equals(suffix) && !jpegStyle.equals(suffix) && !pngStyle.equals(suffix)) {
                log.error("图片格式不正确! : {}", suffix);
                return JsonResult.errorMsg("图片格式不正确!");
            }

            path = minioService.upload(originalFilename + "." + suffix,
                    file.getInputStream(),
                    EnumFileType.IMAGE);
        }

        if (StringUtils.isEmpty(path)) {
            return JsonResult.errorMsg("上传头像失败");
        }

        String finalUserFaceUrl = minioProp.getEndpoint() + path;

        Users userResult = centerUserService.updateUserFace(userId, finalUserFaceUrl);
        UsersVO usersVO = conventUserVO(userResult);

        CookieUtils.setCookie(request, response, USER_INFO, JsonUtils.objectToJson(usersVO), true);

        return JsonResult.ok(userResult);
    }


    @ApiOperation(value = "oss上传头像接口")
    @PostMapping("/oss/upload")
    public JsonResult ossUpload(@ApiParam(value = "上传的文件", required = true) MultipartFile multiFile,
                             @ApiParam(value = "用户id") String userId) throws Exception {

        // 开始上传
        if (ObjectUtils.isEmpty(multiFile)) {
            return JsonResult.errorMsg("文件不能为空!");
        }

        JsonResult result = JsonResult.ok();
        String filename = multiFile.getOriginalFilename();

        String path = "";

        if (StringUtils.hasText(filename)) {
            // 文件重命名  laona-face.png -> ["laona-face", "png"]
            String[] fileNameArr = filename.split("\\.");
            String suffix = fileNameArr[fileNameArr.length - 1];

            path = ossService.upload(multiFile, userId, suffix);
            result.setData(path);

            return result;
        }

        return JsonResult.ok();
    }

}
